package com.bailun91.auth.util;

import com.bailun91.auth.dto.UserAgentDto;
import com.sun.org.apache.bcel.internal.classfile.Unknown;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class UserAgentUtil {

    public static UserAgentDto paseUserAgent(HttpServletRequest request){

        String ua = request.getHeader(Constants.JWT_USER_AGENT);
        //转成UserAgent对象
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        UserAgentDto userAgentDto = new UserAgentDto();

        //获取浏览器信息
        Browser browser = userAgent.getBrowser();
        String browserName = browser.getName();
        System.out.println("浏览器名称："+browserName);
        if (browserName.equals("Unknown")){
            userAgentDto.setBrowserName(ua);
            return userAgentDto;
        }
        userAgentDto.setBrowserName(browserName);

        Version browserVersion = userAgent.getBrowserVersion();
        if (null != browserVersion && null != browserVersion.getVersion()){
            userAgentDto.setBrowserVersion(browserVersion.getVersion());
        }else {
            userAgentDto.setBrowserVersion("");
        }
        //获取系统信息
        OperatingSystem os = userAgent.getOperatingSystem();
        System.out.println("系统信息："+os);
        //系统名称
        String systemName = os.getName();
        System.out.println("系统名称："+systemName);

        String ip = getIpAddress(request);
        userAgentDto.setIp(ip);
        userAgentDto.setSystemName(systemName);
        return  userAgentDto;
    }



    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }


    /**
     * 获取来访者的主机名称
     * @param ip
     * @return
     */
    public static String getHostName(String ip){
        InetAddress inet;
        try {
            inet = InetAddress.getByName(ip);
            return inet.getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "";
    }

}
